#!/usr/bin/python3
#本程序需开启vpn服务方可运行！
import time
import datetime
import serial
from firebase import firebase

#下面这里我可以写一个try语句
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=5)    #ttyUSB串口可在arduinoIDE查看

firebase = firebase.FirebaseApplication('https://opencv3-fish.firebaseio.com/', None)

initTime = time.time()

while True:
    update = firebase.get('/iot-garden-monitoring-system', 'update')
    pi_state = firebase.get('/iot-garden-monitoring-system', 'pi_state')

    # read response back from Arduino
    for i in range (0,3):
        input = ser.readline()
        if("Temp" in str(input)):
            temp_val = input
            temp_val = temp_val[12:-3]
            print("readTemp"+str(temp_val))
        elif("PH" in str(input)):
            PH_val = input
            PH_val = PH_val[9:-2]
            print("readPH"+str(PH_val))
        else:
            TU_val = input
            TU_val = TU_val[9:-5]
            print("readTU"+str(TU_val))
        print ("Read input back: " + str(input))

    if (update == str("1")):
        print ("updating db")
        firebase.put('iot-garden-monitoring-system', 'temperature', str(temp_val))
        firebase.put('iot-garden-monitoring-system', 'humidity', str(PH_val))
        firebase.put('iot-garden-monitoring-system', 'light', str(TU_val))
        firebase.put('iot-garden-monitoring-system', 'moisture', str(TU_val))
        firebase.put('iot-garden-monitoring-system', 'update', str(0))

    time.sleep(1)

